<template>
  <el-dialog
    width="80%"
    title="选择应用"
    :visible.sync="params.visible"
    @close="params.visible = false"
  >
    <el-row :gutter="20">
      <el-col :span="8">
        <compTree
          ref="tree"
          :comp-tree-height="400"
          :tree-show-checkbox="false"
          :tree-data="treeData"
          :highlight-current="true"
          :show-search="false"
          :tree-default-expanded-keys="treeDefaultExpandedKeys"
          :tree-node-select="treeNodeSelect"
        />
      </el-col>
      <el-col :span="8">
        <compTree
          ref="tree2"
          :comp-tree-height="400"
          :tree-show-checkbox="false"
          :tree-data="treeData2"
          :highlight-current="true"
          :show-search="false"
          :tree-default-expanded-keys="tree2DefaultExpandedKeys"
          @treeNodeDbClick="treeNodeDbClick"
        />
      </el-col>
      <el-col :span="8">
        <compTable
          :show-search="false"
          :show-checkbox="false"
          :show-icon="true"
          :table-height="400"
          :table-header="tableHeader"
          :table-data="tableData"
        />
      </el-col>

    </el-row>
    <span
      slot="footer"
      class="dialog-footer"
    >
      <dialog-btn />
    </span>
  </el-dialog>
</template>
<script>
import { getWebComputerList, getTargetByComputerID } from '@/api/bigScreen'
import { SQLTable, ParamArr } from '../../../public/js/paramarr'
import Global from '../../../public/js/global'
export default {
  name: 'SelectTargetText',
  props: {
    params: {
      type: Object,
      default() {
        return {
          targetNames: '', // 指标名称
          ids: '', // 指标id
          istext: false, // 是否通过指标名称匹配
          ismutil: false// 是否多选
        }
      }
    }
  },
  data() {
    return {
      tableHeader: [
        { prop: 'targetName', label: '指标名称' },
        { prop: 'opt', label: '操作', width: '100px', align: 'center',
          render: (h, params) => {
            return h('span', [
              h('el-button', { on: { click: () => { this.onTableDel(params.row) } }}, '删除')
            ])
          }
        }
      ],
      tableData: [],
      treeData: [],
      treeData2: [],
      cmtGroup: 1,
      cmtComputer: 2,
      cmtProgram: 3,
      cmtTargetGroup: 4,
      cmtTarget: 5,
      cmtDynTarget: 6,
      treeDefaultExpandedKeys: [],
      tree2DefaultExpandedKeys: []
    }
  },
  created() {
    this.initWindow()
  },
  methods: {
    initWindow() {
      const vPar = new ParamArr()
      vPar.setStr('IDs', this.params.ids)
      vPar.setBool('IsText', this.params.istext)
      getWebComputerList(vPar).then(vPar => {
        var nodes = []
        var nodeMap = new Map()
        // 分组
        var table = new SQLTable(vPar.getTable('k_group'))
        table.first()
        while (!table.eof()) {
          var pnode = Global.getTreeviewPNode(nodeMap, nodes, table.getValueByName('PID'))
          var node = {}
          // data
          node['id'] = table.getValueByName('ID')
          node['text'] = table.getValueByName('Name')
          node['folder'] = 1
          node['type'] = this.cmtGroup
          // add
          pnode.push(node)
          nodeMap.set(node['id'], node)
          // next
          table.next()
        }
        var selectNode
        // 机器
        // eslint-disable-next-line no-redeclare
        var table = new SQLTable(vPar.getTable('k_computer'))
        table.first()
        while (!table.eof()) {
          // eslint-disable-next-line no-redeclare
          var pnode = Global.getTreeviewPNode(nodeMap, nodes, table.getValueByName('GroupID'))
          // eslint-disable-next-line no-redeclare
          var node = {}
          // data
          node['id'] = table.getValueByName('ID')
          node['text'] = table.getValueByName('IP')
          node['icon'] = Global.getSystemIconStr(table.getValueByName('System').trim())
          node['sText'] = table.getValueByName('IP')
          node['type'] = this.cmtComputer
          if (vPar.getStr('ComputerID') === node['id']) {
            selectNode = node
            this.treeDefaultExpandedKeys.push(table.getValueByName('GroupID'))
          }
          // add
          pnode.push(node)
          nodeMap.set(node['id'], node)
          // next
          table.next()
        }

        var rows = []
        // eslint-disable-next-line no-redeclare
        var table = new SQLTable(vPar.getTable('k_target'))
        table.first()
        while (!table.eof()) {
          var row = {}
          // data
          row['id'] = table.getValueByName('TargetID')
          row['programID'] = table.getValueByName('ProgramID')
          row['computerID'] = table.getValueByName('ComputerID')
          // view
          var sTarget = ''
          // eslint-disable-next-line eqeqeq
          if (table.getValueByName('PName') == '') { sTarget = table.getValueByName('Name') } else { sTarget = Global.strFormat('{0}.{1}', table.getValueByName('PName'), table.getValueByName('Name')) }
          row['targetName'] = Global.strFormat('[{0}][{1}][{2}]', table.getValueByName('IP'), table.getValueByName('ProgramName'), sTarget)
          rows.push(row)
          table.next()
        }
        this.treeData = nodes
        this.tableData = rows
        this.$refs.tree.setSelect(vPar.getStr('ComputerID'))
        if (selectNode) { this.treeNodeSelect(selectNode) }
      })
    },
    treeNodeSelect(node) {
      // eslint-disable-next-line eqeqeq
      if (node.type == this.cmtComputer) {
        // 获取数据
        var vPar = new ParamArr()
        vPar.setStr('ComputerIDs', node.id)
        vPar.setBool('Web', true)
        vPar.setStr('sText', node['sText'])
        this.$refs.tree2.showLoading()
        getTargetByComputerID(vPar).then(vPar => {
          var nodes = []
          var nodeMap = new Map()
          // 数据
          // 应用
          var table = new SQLTable(vPar.getTable('k_program'))
          table.first()
          while (!table.eof()) {
            var pnode = Global.getTreeviewPNode(nodeMap, nodes, table.getValueByName('ComputerID'))
            var node = {}
            // data
            node['id'] = table.getValueByName('ID')
            node['text'] = table.getValueByName('Name')
            node['icon'] = 'yingyong'
            node['sText'] = `[${vPar.getStr('sText')}][${table.getValueByName('Name')}]`
            node['type'] = this.cmtProgram
            // add
            pnode.push(node)
            nodeMap.set(node['id'], node)

            this.addTargetGroup(nodeMap, nodes, node, 1)
            this.addTargetGroup(nodeMap, nodes, node, 0)
            // next
            table.next()
          }

          // eslint-disable-next-line no-redeclare
          var table = new SQLTable(vPar.getTable('k_target'))
          table.first()
          while (!table.eof()) {
            // eslint-disable-next-line eqeqeq
            if (table.getValueByName('Dynamic') == 0) {
            // eslint-disable-next-line no-redeclare
              var pnode = Global.getTreeviewPNode(nodeMap, nodes, Global.strFormat('{0}{1}', table.getValueByName('ProgramID'), table.getIntByName('Type')))
            } else {
              // eslint-disable-next-line no-redeclare
              var pnode = Global.getTreeviewPNode(nodeMap, nodes, table.getValueByName('DynamicPID'))
            }
            // eslint-disable-next-line no-redeclare
            var node = {}
            // data
            node['id'] = table.getValueByName('ID')
            node['text'] = table.getValueByName('Name')
            node['icon'] = 'zhibiao'
            node['programID'] = table.getValueByName('ProgramID')
            node['computerID'] = table.getValueByName('ComputerID')
            // eslint-disable-next-line eqeqeq
            if (table.getValueByName('Dynamic') == 0) {
              node['type'] = this.cmtTarget
              var pN = nodeMap.get(table.getValueByName('ProgramID'))
              if (!pN) {
                table.next()
                continue
              }
              node['sText'] = Global.strFormat('{0}[{1}]', pN['sText'], table.getValueByName('Name'))
            } else {
              // 虚拟指标
              node['type'] = this.cmtDynTarget
              node['icon'] = 'zhibiaoxuni'
              // eslint-disable-next-line no-redeclare
              var pN = nodeMap.get(table.getValueByName('DynamicPID'))
              if (!pN) {
                table.next()
                continue
              }
              var sText = pN['sText']
              sText = sText.substr(0, sText.length - 1)
              node['sText'] = Global.strFormat('{0}.{1}]', sText, table.getValueByName('Name'))
            }
            // add
            pnode.push(node)
            nodeMap.set(node['id'], node)
            table.next()
          }
          this.treeData2 = nodes
          this.$refs.tree2.hideLoading()
        })
      }
    },
    treeNodeDbClick(node) {
      var row = {}
      if (node.type === this.cmtTarget || node.type === this.cmtDynTarget) {
        // data
        row['id'] = node.id
        row['programID'] = node.programID
        row['computerID'] = node.computerID
        // view
        row['targetName'] = node.sText
        // this.tableData = rows
        if (this.params.ismutil === false) this.tableData = []
        this.tableData.push(row)
      }
    },
    onTableDel(row) {
      this.tableData = this.tableData.filter(item => item.id !== row.id)
    },
    addTargetGroup(nodeMap, nodes, node, iType) {
      var pnode = Global.getTreeviewPNode(nodeMap, nodes, node['id'])
      var subnode = {}
      // data
      subnode['id'] = `${node['id']}${iType}`
      // eslint-disable-next-line eqeqeq
      if (iType == 1) { subnode['text'] = '操作' } else { subnode['text'] = '指标' }
      subnode['type'] = this.cmtTargetGroup
      subnode['sText'] = node['sText']
      subnode['folder'] = 1
      pnode.push(subnode)
      nodeMap.set(subnode['id'], subnode)
    },
    confirm() {
      if (this.tableData.length === 0) return this.$message.warning('请选择指标!')
      var text = ''
      var ids = ''
      var data = {}
      this.tableData.forEach(item => {
        text = Global.strFormat('{0},{1}', text, item['targetName'])
        ids = Global.strFormat('{0},{1}', ids, item['id'])
      })
      if (ids !== '') {
        ids = ids.substr(1, ids.length - 1)
      }
      if (text !== '') {
        text = text.substr(1, text.length - 1)
      }
      data = { text, ids }
      // 如果当前传入回调则使用回调
      if (this.params.confirm !== undefined) {
        this.params.confirm(data)
      } else {
        this.$emit('confirm', data)
      }
      this.treeDefaultExpandedKeys = []
    }
  }
}
</script>
